using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Linq;

namespace Lib.Helper
{
    public static class EventAggregator
    {
       
        private static Dictionary<string, List<Action<Object>>> _subscribers;
        private static Dictionary<string, List<Action<Object,Object>>> _subscribers2;

        static EventAggregator()
        {
            _subscribers = new Dictionary<string, List<Action<object>>>();
            _subscribers2 = new Dictionary<string, List<Action<object, object>>>();
        }
        


        public static  void RegisterMessage(string EventName,Action<Object> Action)
        {
            if (! _subscribers.ContainsKey(EventName))
                _subscribers.Add(EventName, new List<Action<object>>());
          if (! _subscribers[EventName].Any(a=>a.Method.GetHashCode()==Action.Method.GetHashCode()))
              _subscribers[EventName].Add(Action);
        }


        public static void RegisterMessage(string EventName, Action<Object,Object> Action)
        {
            if (!_subscribers2.ContainsKey(EventName))
                _subscribers2.Add(EventName, new List<Action<object,object>>());
            if (!_subscribers2[EventName].Any(a => a.Method.GetHashCode() == Action.Method.GetHashCode()))
                _subscribers2[EventName].Add(Action);
        }


        public static void PublishMessage(string EventName,Object param)
        {
            if (_subscribers.ContainsKey(EventName))
                foreach (var action in _subscribers[EventName])
                {
                    if (action != null)
                    {
                        action(param);
                        UnRegisterMessage(EventName);
                    }
                        
                }
        }

        public static void PublishMessage(string EventName, Object param1,Object param2)
        {
            if (_subscribers2.ContainsKey(EventName))
                foreach (var action in _subscribers2[EventName])
                {
                    if (action != null)
                    {
                        action(param1,param2);
                    }

                }
        }

        private static void UnRegisterMessage(string  EventName)
        {
            if (_subscribers.ContainsKey(EventName))
                _subscribers.Remove(EventName);
        }

        private static void UnRegisterMessage2(string EventName)
        {
            if (_subscribers2.ContainsKey(EventName))
                _subscribers2.Remove(EventName);
        }
    }




    public static class ControlExtensions
    {
        public static bool HasFocus(this Control aControl)
        {
            return System.Windows.Input.FocusManager.GetFocusedElement() == aControl;
        }
    }



}
